import Vue from 'vue'
import Vuex from 'vuex'
import request from "../utils/request"
import createPersistedState from "vuex-persistedstate";
Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    listArr:[],
    Allchecked:false,
    infodata:{}
  },
  mutations: {
    getdata(state,payload){
       state.listArr=payload;
    },
    addData(state,payload){
      let istrue =state.listArr.find((item) => {
        return item.id==payload
      })
      if(istrue){

        state.listArr.forEach((item,index) => {
          if(item.id===payload.id){
           item.name=payload.name
           item.user=payload.user
           item.info=payload.info
           item.sex=payload.sex
           item.date=payload.date
          }
       })
      }else {
        state.listArr.unshift(payload)
      }
      
    },
    delData(state,payload){
      state.listArr.forEach((item,index) => {
         if(item.id===payload){
          state.listArr.splice(index, 1)
         }
      })
    },
    allchecked(state,payload){
      state.listArr.forEach((item,index) => {
        item.flag=payload
        
     })
    },
    checkeditem(state,payload){
      state.listArr.forEach((item,index) => {
        if(item.id===payload){
         item.flag=! item.flag
        }
     })
      state.Allchecked=state.listArr.every(item=>item.flag)
    },
    // 删除选中数据
    delchecked(state,payload){
      for (let i = 0; i < state.listArr.length; i++) {
        state.listArr.forEach((item,index) => {
          if(item.flag){
            state.listArr.splice(index, 1)
          }
        })
      }
    },
    // 获取信息
    getinfo(state,payload){
      state.listArr.forEach((item,index) => {
        if(item.id===payload){
        state.infodata=item
        }
     })
    },
    editData(state,payload){

    },
  },
  actions: {
    getData(context,payload){
        request.get("/api/list").then((res) => {
          context.commit("getdata",res.data.list)
        })
    }
  },
  modules: {
  },
  plugins: [createPersistedState()],
})
